Jump Game
Question
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
Analysis
遍历整个数组,利用reach标记当前可达的最大脚标,假如i>reach则停止遍历,判断此时i是否等于数组长度,假如可达的话,i应该恰好在des处停止
注意: i<=reach,而非 i<reach,初始条件下 i=reach=0
Code
- Greedy
|
|
Gas Station
Question
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station’s index if you can travel around the circuit once, otherwise return -1.
Analysis
一开始只想着从每个节点开始遍历一圈,确认gas_total>=cost_total,TLE
- 假如当前车站A(begin)无法到达B,则A-B的所有车站都无法到达B,begin从i+1开始
- gas_total>=cost_total,即有路可寻
Code
- Greedy Version
|
|
- TLE version
|
|